import { Row, Col, Upload, Grid, message, Button } from 'antd';
import React, { useRef, useEffect, useState, useMemo } from 'react';
import { getFetch, formFetch } from '@/utils/doFetch';
import Images from './Images'
import { PlusOutlined, EyeOutlined, LoadingOutlined, ScanOutlined, DeleteOutlined } from '@ant-design/icons';
import wx from 'weixin-js-sdk';
import styles from './index.less'


function getBase64Image(url, callback) {
  var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    img = new Image();
  //为了解决跨域，可以直接img.crossOrigin=''就能解决图片跨域问题
  img.crossOrigin = '';
  img.onload = function () {
    canvas.height = (img.height / img.width) * 1080;
    canvas.width = 1080;
    ctx.drawImage(img, 0, 0, 1080, (img.height / img.width) * 1080);
    var dataURL = canvas.toDataURL('image/jpg');
    callback.call(this, dataURL);
    canvas = null;
  }
  img.src = url;
}
const { useBreakpoint } = Grid;

let Recognition = ({ value, onChange, item, scanResult }) => {
  const [visible, setVisible] = useState(false);
  const [cururl, setcururl] = useState();
  const [action, setaction] = useState();
  const [load, sl] = useState(false);
  const screens = useBreakpoint();

  useEffect(() => {
    getFetch({ url: "/wbn-api/ai_baidu", params: {} }).then(res => {
      setaction(`/baiduapi/rest/2.0/ocr/v1/business_license?access_token=${res.data.access_token}`)
    })
    getFetch({ url: "/wbn-api/wechat/signature", params: { url: document.URL } }).then(res => {
      if (res.code == 0) {
        wx.config({
          debug: false,
          appId: res.data.app_id,
          timestamp: res.data.timestamp,
          nonceStr: res.data.nonce_str,
          signature: res.data.signature,
          jsApiList: [
            "scanQRCode",
            "chooseImage",
            "getLocalImgData"
          ]
        })
        wx.ready(function () {
        })
        wx.error(function (err) {
        })
      }
    })
  }, [])

  useMemo(() => {
    if (value?.origin_url) {
      let url = value.origin_url;
      getBase64Image(url, function (base64Img) {
        setcururl(base64Img)
      });
    }
  }, [value]);

  function beforeUpload(file) {
    sl(true)
    let size = 5;
    const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传.jpg/.jpeg/.png图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < size;
    if (!isLt2M) {
      message.error('图片大小须小于' + size + 'MB!');
      onChange(null)
    }
    return isJpgOrPng && isLt2M;
  }

  const props = {
    name: "file",
    action: item.serverURL ? item.serverURL : window?.dataconfig?.serverURL,
    listType: "picture-card",
    accept: ".jpg,.png,.jpeg,",
    multiple: false,
    beforeUpload: beforeUpload,
    showUploadList: false,
    onChange(info) {
      let { file, fileList } = info;
      let { status } = file;
      if (fileList.length > 0) {
        if (status == 'done' || status == 'removed') {
          onChange(file?.response?.data);
        } else if (status == 'error') {
          message.error(`${info.file.name} 上传失败`);
        }
      } else {
        setcururl(null);
        onChange(null)
      }
      setTimeout(() => {
        sl(false)
      }, 1000)
    }
  };


  const uploadBtn = (<div>
    <PlusOutlined />
    <div style={{ marginTop: 8 }}>上传</div>
  </div>)

  let RenderImg = ({ cururl }) => {
    return <div className="hoverable" style={{ width: 104, height: 104, padding: 8 }}>
      <div style={{
        width: "100%",
        height: "100%",
        backgroundImage: `url(${cururl})`,
        backgroundSize: "contain",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center"
      }}>
        <div className="iconcon center">
          {
            load && <LoadingOutlined style={{ color: "#fff", fontSize: 20 }} />
          }
          {
            !load && <EyeOutlined style={{ color: "#fff", fontSize: 20, marginRight: 10, textShadow: "2px 2px 2px #000" }} onClick={(e) => {
              e.stopPropagation()
              setVisible(true);
            }} />
          }
          {
            !load && <DeleteOutlined style={{ color: "#fff", fontSize: 20, textShadow: "2px 2px 2px #000" }} onClick={(e) => {
              e.stopPropagation()
              setcururl(null)
              onChange(null);
            }} />
          }
        </div>
        <div style={{ position: "absolute", left: 114, bottom: 9 }}>
          {
            !load && <Button
              icon={<ScanOutlined />}
              onClick={(e) => {
                e.stopPropagation()
                if (!cururl) {
                  message.warn("请先上传营业执照！")
                  return
                }
                let params = new FormData();
                params.append('image', encodeURI(cururl));

                sl(true)
                fetch(action, {
                  method: 'POST',
                  body: params
                })
                  .then(response => response.json())
                  .catch(error => console.error('Error:', error))
                  .then(response => {
                    //response.words_result
                    if (response.words_result) {
                      message.success("识别成功！模糊照片请仔细核对识别结果是否无误。");
                      let formatres = {
                        "name": response.words_result["单位名称"].words,
                        "legal_person": response.words_result["法人"].words,
                        "address": response.words_result["地址"].words,
                        "enterprise_credit_code": response.words_result["社会信用代码"].words
                      }
                      scanResult(formatres)
                    }
                    sl(false)
                  });
              }}
            >识别执照</Button>
          }

        </div>
      </div>
    </div>
  }

  const dataURLtoFile = (dataurl, filename) => {
    let arr = dataurl.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    //转换成file对象
    return new File([u8arr], filename, { type: mime });
    //转换成成blob对象
    //return new Blob([u8arr],{type:mime});
  }


  return (
    <div style={{ display: "flex", justifyContent: "flex-start", alignItems: "center", minHeight: 114, minWidth: 114 }}>
      <Images src={cururl} width={0} height={0} preview={{
        visible,
        onVisibleChange: (visibles) => {
          if (visible) {
            setVisible(false);
          }
        }

      }} />
      {//(screens.xs && !screens.sm)
        false ?
          <div>
            {
              cururl ?
                <div style={{ border: "1px solid #d9d9d9", margin: "0 8px 8px 0px" }}>
                  <RenderImg cururl={cururl} />
                </div>
                :
                <div className="ant-upload ant-upload-select ant-upload-select-picture-card center" onClick={() => {
                  sl(true)
                  wx?.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (result) {
                      var localIds = result.localIds;
                      localIds.map(it => {
                        wx.getLocalImgData({
                          localId: it, // 图片的localID
                          success: function (response) {
                            var localData = response.localData; // localData是图片的base64数据，可以用img标签显示
                            if (localData.substr(0, 5) != 'data:') {
                              localData = 'data:image;base64,' + localData;
                            }
                            setcururl(localData)

                            let file = dataURLtoFile(localData, "images.jpg")
                            let params = new FormData();
                            params.append('file', file);

                            fetch("/wbn-api/file", {
                              method: 'POST',
                              body: params,
                            }).then(res => {
                              return res.json();
                            }).then(res => {
                              if (res.code != 0) {
                                message.error("只能上传.jpg/.jpeg/.png图片!")
                                return
                              }
                              onChange(res?.data);
                            })
                            setTimeout(() => {
                              sl(false)
                            }, 1000)
                          }
                        });
                      })
                    }
                  });
                }}>
                  {uploadBtn}
                </div>

            }
          </div>
          :
          <Upload {...props} style={{ width: '100%' }}>
            {
              cururl ? <RenderImg cururl={cururl} /> : uploadBtn
            }
          </Upload>
      }



    </div>

  )
}

export default Recognition
